import json
from datetime import datetime

from django.db import IntegrityError
from django.db.models.fields import return_None
from django.shortcuts import render
from django.http import JsonResponse
from db_man_app.models import Student, Class, Department, Major


def get_all(request):
    print("获取全部学生信息")
    # 查询所有学生信息，并使用select_related优化外键查询
    students = Student.objects.all().select_related('major', 'class_field', 'department')
    # 将查询结果格式化为前端需要的格式
    table_data = []
    for student in students:
        table_data.append({
            'student_id': student.student_id,
            'name': student.name,
            'gender': student.gender,  # 假设M表示男，F表示女
            'birth_date': student.birth_date.strftime('%Y-%m-%d'),
            'grade': student.grade,
            'major': student.major.major_name,
            'class': student.class_field.class_name,
        })
    # 返回JSON响应
    return JsonResponse({'tableData': table_data}, safe=False)


#以下是添加表单里，需要自动填年级专业等信息，从数据库中读取班级，对应的年级，专业信息。
def get_class_form(request):
    classes = Class.objects.all()
    data = [
        {'class_id': cls.class_id, 'class_name': cls.class_name, 'grade': cls.grade, 'major_name': cls.major.major_name}
        for cls in classes]
    return JsonResponse(data, safe=False)


#向数据库加一条
def add_one(request):
    data = json.loads(request.body)
    student_id = data['student_id']
    gender = data['gender']
    name = data['name']
    grade = data['grade']
    class_id = data['class_id']
    birth_str = data['birth_date']
    birth_date = datetime.strptime(birth_str, '%Y-%m-%dT%H:%M:%S.%fZ').date()
    try:
        class_obj = Class.objects.get(class_id=class_id)
        major_id = class_obj.major_id
        department_id = class_obj.department_id
        Student.objects.create(
            student_id=student_id,
            name=name,
            grade=grade,
            major_id=major_id,
            department_id=department_id,
            class_field=class_obj,
            birth_date=birth_date,
            gender=gender,
        )
    except IntegrityError:
        return JsonResponse(0, safe=False)
    return JsonResponse(1, safe=False)


#修改的学生信息
def updata_one(request):
    data = json.loads(request.body)
    student_id = data['student_id']
    gender = data['gender']
    name = data['name']
    grade = data['grade']
    class_id = data['class_id']
    birth_date = data['birth_date']
    if isinstance(class_id, int):
        class_obj = Class.objects.get(class_id=class_id)
    else:
        class_obj = Class.objects.get(class_name=class_id)
    try:
        major_id = class_obj.major_id
        department_id = class_obj.department_id
        Student.objects.filter(student_id=student_id).update(
            student_id=student_id,
            name=name,
            grade=grade,
            major_id=major_id,
            department_id=department_id,
            class_field=class_obj,
            birth_date=birth_date,
            gender=gender,
        )
    except IntegrityError:
        return JsonResponse(0, safe=False)
    return JsonResponse(1, safe=False)


#删除学生
def del_one(request):
    data = json.loads(request.body)
    student_id = data['del_id']
    try:
        Student.objects.filter(student_id=student_id).delete()
        return JsonResponse(1, safe=False)
    except IntegrityError:
        return JsonResponse(0, safe=False)


#通过班级名称获取id
def get_class_name(request):
    try:
        data = json.loads(request.body)
        class_obj = Class.objects.filter(class_name=data).first()
        return JsonResponse({'class_id': class_obj.class_id})
    except IntegrityError:
        return JsonResponse(0, safe=False)


def search(request):
    try:
        data = json.loads(request.body)
        student_id = data.get('student_id', '').strip()
        college_name = data.get('college_name', '').strip()
        class_name = data.get('class_name', '').strip()

        query_conditions = {}

        if student_id:
            query_conditions['student_id'] = student_id
        if college_name:
            try:
                college = Major.objects.get(major_name=college_name)
                query_conditions['major_id'] = college.major_id
            except Major.DoesNotExist:
                return JsonResponse({'searchData': []}, safe=False)
        if class_name:
            try:
                class_obj = Class.objects.get(class_name=class_name)
                query_conditions['class_field_id'] = class_obj.class_id
            except Class.DoesNotExist:
                return JsonResponse({'searchData': []}, safe=False)
        students_query = Student.objects.select_related(
            'class_field',
            'major',
            'department'
        )

        if query_conditions:
            students_query = students_query.filter(**query_conditions)
        # 构造返回的数据，包含学生信息 + 关联的班级、专业、学院名称
        table_data = []
        for student in students_query:
            table_data.append({
                'student_id': student.student_id,
                'name': student.name,
                'gender': student.gender,
                'birth_date': student.birth_date.strftime('%Y-%m-%d') if student.birth_date else None,
                'grade': student.grade,
                'class': student.class_field.class_name if student.class_field else None,
                'major': student.major.major_name if student.major else None,
                'department_name': student.department.department_name if student.department else None,
            })

        return JsonResponse({'searchData': table_data}, safe=False)
    except Exception as e:
        import logging
        logging.error(f"Search error: {str(e)}")
        return JsonResponse({'searchData': []}, safe=False)